package com.lwg.vhr.config;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.lwg.vhr.model.Hr;
import com.lwg.vhr.service.impl.HrServiceImpl;
import com.lwg.vhr.utils.RespBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.*;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author: lwg
 * @Date: 2021/7/24 17:33
 * @Description: SpringSecurity配置类
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private HrServiceImpl hrService;

    @Autowired
    private CustomFilterInvocationSecurityMetadataSource customFilterInvocationSecurityMetadataSource;

    @Autowired
    private CuestomHRRMyDecisionMannager cuestomHRRMyDecisionMannager;

    /**
     * @title 密码加密
     * @description
     * @author lwg
     * @updateTime 2021/7/24 17:32
     */
    @Bean
    PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * @title config类
     * @description 创建一个config把service注入进去
     * @author lwg
     * @updateTime 2021/7/24 17:32
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(hrService);
    }

    /**
     * @author: lwg
     * @Date: 2021/7/27 23:36
     * @Description: 用户在postman中没有登录报错的现象
     */
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/login");
    }
    /**
     * @title
     * @description 配置登录成功或失败向前端传送json数据
     * @author lwg
     * @updateTime 2021/7/24 18:37
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                //所有的请求url都是登录之后才可以访问
                //.anyRequest().authenticated()
                //配置登录访问的权限
                .withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {

                    @Override
                    public <O extends FilterSecurityInterceptor> O postProcess(O object) {
                        object.setAccessDecisionManager(cuestomHRRMyDecisionMannager);
                        object.setSecurityMetadataSource(customFilterInvocationSecurityMetadataSource);
                        return object;
                    }
                })
                .and()
                //表单登录
                .formLogin()
                //修改前端默认的登录的属性
                .usernameParameter("username")
                .passwordParameter("password")

                //登录的url(controller层的路径)
                .loginProcessingUrl("/doLogin")
                .loginPage("/login")
                //登录成功后的处理
                .successHandler(new AuthenticationSuccessHandler() {
                    @Override
                    public void onAuthenticationSuccess(HttpServletRequest req, HttpServletResponse resp, Authentication authentication) throws IOException, ServletException {
                        //登录成功返回一端json数据
                        resp.setContentType("application/json; charset=UTF-8");
                        //输出
                        PrintWriter out=resp.getWriter();
                        //登陆成功的hr信息  获取当前用户信息
                        Hr hr = (Hr) authentication.getPrincipal();
                        hr.setPassword(null);
                        RespBean ok = RespBean.ok("登录成功", hr);
                        //将hr实体类信息转换成json字符串数据给到输出流中
                        String s = new ObjectMapper().writeValueAsString(ok);
                        out.write(s);
                        //输出完后将管道中的剩余数据强制输出，清空管道
                        out.flush();
                        out.close();
                    }
                })
                //登录失败后的处理
                .failureHandler(new AuthenticationFailureHandler() {
                    @Override
                    public void onAuthenticationFailure(HttpServletRequest req, HttpServletResponse resp, AuthenticationException e) throws IOException, ServletException {
                        resp.setContentType("application/json; charset=UTF-8");
                        PrintWriter out=resp.getWriter();
                        //此时登录失败就不需要将书体类数据返回了
                        RespBean respBean = RespBean.error("登录失败!");
                        if (e instanceof LockedException){
                            respBean.setMsg("账户被锁定，请联系管理员！");
                        }else if (e instanceof CredentialsExpiredException){
                            respBean.setMsg("密码过期，请联系管理员！");
                        }else if (e instanceof AccountExpiredException){
                            respBean.setMsg("账户过期，请联系管理员！");
                        }else if (e instanceof DisabledException){
                            respBean.setMsg("账户被禁用，请联系管理员！");
                        }else if (e instanceof BadCredentialsException){
                            respBean.setMsg("用户名或者密码输入错误，清联系管理员！");
                        }
                        out.write(new ObjectMapper().writeValueAsString(respBean));
                        out.flush();
                        out.close();
                    }
                })
                //登录后相关的接口可以访问
                .permitAll()
                .and()
                .logout()
                //注销成功后返回提示信息
                .logoutSuccessHandler(new LogoutSuccessHandler() {
                    @Override
                    public void onLogoutSuccess(HttpServletRequest req, HttpServletResponse resp, Authentication authentication) throws IOException, ServletException {
                        resp.setContentType("application/json;charset=utf-8");
                        PrintWriter out = resp.getWriter();
                        RespBean respBean = RespBean.ok("注销成功");
                        String s = new ObjectMapper().writeValueAsString(respBean);
                        out.write(s);
                        out.flush();
                        out.close();
                    }
                })
                .permitAll()
                .and()
                .csrf().disable()

                //未登录就在前台输入访问路径
                .exceptionHandling().authenticationEntryPoint(new AuthenticationEntryPoint() {
            @Override
            public void commence(HttpServletRequest req, HttpServletResponse resp,
                                 AuthenticationException authException) throws IOException, ServletException {
                resp.setContentType("application/json;charset=utf-8");
                resp.setStatus(401);
                PrintWriter out = resp.getWriter();
                RespBean error = RespBean.error("访问失败");
                if (authException instanceof InsufficientAuthenticationException) {
                    error.setMsg("非法路径访问,请登录后再进行操作!!!");
                }
                out.write(new ObjectMapper().writeValueAsString(error));
                out.flush();
                out.close();
            }
        });

    }
}
